﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;

namespace DataPump
{
    public abstract class IResource
    {
        public int total, recrod, jumpwitherror,jumpwithtime,jumpwithempty,jumpwithganji, repeat;
        protected string[] Forbiddens = null;
        protected string ConnectStr = "";
        protected Dictionary<int, string> dict = new Dictionary<int, string>();
        public IResource(string constr)
        {
            SetDict();
            string forbiddens = ConfigurationManager.AppSettings["forbidden"];
            if (!String.IsNullOrEmpty(forbiddens))
            {
                Forbiddens = forbiddens.Split('@');
            }
            else
            {
                throw new Exception("forbiddens配置节为空");
            }
            this.ConnectStr = constr;
        }
        protected string Pickbody(string html)
        {
            string body = new Regex("\\<body.*?\\>.*?\\</body\\>").Match(html).Value;
            return body;
        }
        private decimal GetMinSalary(string salary)
        {
            if (salary.Trim() == "面议" || String.IsNullOrEmpty(salary.Trim()))
            {
                return 0;
            }
            else
            {
                string s = new Regex("\\d+").Match(salary).Value;
                decimal res = 0;
                if (decimal.TryParse(s, out res))
                {
                    return res;
                }
                return 0;
            }
        }
        private decimal GetMaxSalary(string salary)
        {
            return 0;
        }
        private decimal GetSalaryPeriod(string salary)
        {
            if (salary.Contains("小时"))
            {
                return 160;
            }
            if (salary.Contains("天"))
            {
                return 40;
            }
            else if (salary.Contains("周"))
            {
                return 8;
            }
            else // (salary.Contains("月"))
            {
                return 1;
            }
        }
        public abstract void Do();
        protected abstract void SetDict();
        protected abstract void Analysts(string html, string uri, ref int count);
        protected abstract int PositionTypeMapping(string uri);
        protected abstract string PositionNameMapping(string uri);
        public abstract int WorkAreaMapping(string str);
        protected abstract int CompanyBusinessMapping(string orgstr);
        protected abstract int CompanyTypeMapping(string orgstr);
        protected abstract int CompanydimensionsMapping(string orgstr);
        protected abstract int GenderMapping(string gender);
        protected abstract int DegreeMapping(string degree);
        protected abstract int VacancyMapping(string vacancy);
        protected abstract int ExperiencedMapping(string experience);

        //protected void PostData(ref int count, List<Info> data)
        //{
        //    string agent = Common.GetRecruiter();
        //    foreach (var item in data)
        //    {
        //        using (SqlConnection con = new SqlConnection(ConnectStr))
        //        {
        //            con.Open();
        //            SqlTransaction tran = con.BeginTransaction();
        //            SqlCommand com = con.CreateCommand();
        //            com.Transaction = tran;
        //            try
        //            {
        //                int depositCompanyId = PostNewDepositCompany(com, agent, item.CompanyName, item.CopAbout, item.CopBusiness, item.CopType, item.CopDimensions);
        //                int recruitId = PostNewRecruitSheet(com, item.Caption, agent, depositCompanyId, 1, item.ContactMan, item.ContactPhone, item.Address);
        //                PostNewPosition(com, recruitId, item.PositionName, item.Vacancy, item.PositionType, item.Salry, "不限", item.Degree, item.Experience, item.PositionDescript);
        //                tran.Commit();
        //                com.Dispose();
        //            }
        //            catch (Exception e)
        //            {
        //                tran.Rollback();
        //                Console.WriteLine("添加第" + --count + "条数据异常");
        //                using (System.IO.StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "postdata.txt"))
        //                {
        //                    sw.WriteLine(e.ToString());
        //                }
        //            }
        //        }
        //    }
        //}
        protected int PostData(Info item)
        {
            string agent = Common.GetRecruiter();

            using (SqlConnection con = new SqlConnection(ConnectStr))
            {
                con.Open();
                SqlTransaction tran = con.BeginTransaction();
                SqlCommand com = con.CreateCommand();
                com.Transaction = tran;
                try
                {
                    if (IsNotRecord(com, HashAlgorithm.Encrypt(item.Caption + ";" + item.ContactMan + ";" + item.ContactPhone, EncryptMode.md5)))
                    {
                        int depositCompanyId = PostNewDepositCompany(com, agent, item.CompanyName, item.CopAbout, item.CopBusiness, item.CopType, item.CopDimensions);

                        int recruitId = PostNewRecruitSheet(com, item.Caption, agent, depositCompanyId, 1, item.ContactMan, item.ContactPhone, item.Address, HashAlgorithm.Encrypt(
                            item.Caption + ";" + item.ContactMan + ";" + item.ContactPhone, EncryptMode.md5));
                        PostNewPosition(com, recruitId, item.PositionName, item.Vacancy, item.PositionType, item.Salry, "不限", item.Degree, item.Experience, item.PositionDescript);
                        tran.Commit();
                        com.Dispose();
                        Console.Write("，本条数据成功添加到数据库");
                        return 1;
                    }
                    else
                    {
                        Console.Write("，本条数据重复");
                        com.Dispose();
                    }
                }
                catch (Exception e)
                {
                    tran.Rollback();
                    Console.Write("，本条数据添加异常");
                    using (System.IO.StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "postdata.txt"))
                    {
                        sw.WriteLine(e.ToString());
                    }
                }
                Console.WriteLine();
            }
            return 0;
        }
        private bool IsNotRecord(SqlCommand com, string querycode)
        {
            com.Parameters.Clear();
            com.CommandText = "select 1 from recruitsheet where querycode = @querycode";
            com.Parameters.Add(new SqlParameter("@querycode", querycode));
            object res = com.ExecuteScalar();
            return res == null;
        }
        private int PostNewDepositCompany(SqlCommand com, string agent, string companyName, string companyDetail, string bussiness, string copType, string copDim)
        {
            com.Parameters.Clear();
            com.CommandText = "insert into depositcompany(agent,companyname,companydetail,postdate,companybusiness,companytype,companydimensions,templete) values(@agent,@companyname,@companydetail,getdate(),@companybusiness,@companytype,@companydimensions,0) select SCOPE_IDENTITY()";
            com.CommandType = System.Data.CommandType.Text;
            com.Parameters.Add(new SqlParameter("@agent", agent));
            com.Parameters.Add(new SqlParameter("@companyname", companyName));
            com.Parameters.Add(new SqlParameter("@companydetail", companyDetail));
            com.Parameters.Add(new SqlParameter("@companybusiness", CompanyBusinessMapping(bussiness)));
            com.Parameters.Add(new SqlParameter("@companytype", CompanyTypeMapping(copType)));
            com.Parameters.Add(new SqlParameter("@companydimensions", CompanydimensionsMapping(copDim)));
            object res = com.ExecuteScalar();
            return Convert.ToInt32(res);
        }
        private int PostNewRecruitSheet(SqlCommand com, string caption, string agent, int depositionCompanyId, int recruitType, string Contact, string ContactPhone, string address, string querycode)
        {
            com.Parameters.Clear();
            com.CommandText = "insert into recruitsheet(caption,recruiter,depositcompanyId,recruitType,recruitSubject,contact,contactphone,workarea,workaddress,publishdate,customermanager,templete,isverify,enableemail,querycode,refresh,Source) values(@caption,@recruiter,@depositcompanyId,@recruitType,@recruitSubject,@contact,@contactphone,@workarea,@workaddress,getdate(),null,0,1,0,@querycode,getdate(),-1)select SCOPE_IDENTITY()";
            com.CommandType = System.Data.CommandType.Text;
            com.Parameters.Add(new SqlParameter("@caption", caption));
            com.Parameters.Add(new SqlParameter("@recruiter", agent));
            com.Parameters.Add(new SqlParameter("@depositcompanyId", depositionCompanyId));
            com.Parameters.Add(new SqlParameter("@recruitType", recruitType));
            if (new Random().Next(0, 100) < 10)
            {
                com.Parameters.Add(new SqlParameter("@recruitSubject", (object)1));
            }
            else
            {
                com.Parameters.Add(new SqlParameter("@recruitSubject", (object)0));
            }
            com.Parameters.Add(new SqlParameter("@contact", Contact));
            com.Parameters.Add(new SqlParameter("@contactphone", ContactPhone));
            com.Parameters.Add(new SqlParameter("@workarea", WorkAreaMapping(address)));
            com.Parameters.Add(new SqlParameter("@workaddress", address));
            com.Parameters.Add(new SqlParameter("@querycode", querycode));
            object res = com.ExecuteScalar();
            return Convert.ToInt32(res);
        }
        private void PostNewPosition(SqlCommand com, int recruitId, string positionName, string vacancy, int positionType, string salary, string gender, string degree, string experienced, string positionDesctipt)
        {
            com.Parameters.Clear();
            com.CommandText = "insert into position(recruitId,positionName,vacancy,positiontype,minsalary,maxsalary,period,gender,degree,experienced,positiondescript,scantime,operatorname,trusteeship,isindex,positionpriority,positionlevel) values(@recruitId,@positionName,@vacancy,@positiontype,@minsalary,@maxsalary,@period,@gender,@degree,@experienced,@positiondescript,0,'',0,0,0,0) select SCOPE_IDENTITY()";
            com.CommandType = System.Data.CommandType.Text;
            com.Parameters.Add(new SqlParameter("@recruitId", recruitId));
            com.Parameters.Add(new SqlParameter("@positionName", positionName));
            com.Parameters.Add(new SqlParameter("@vacancy", VacancyMapping(vacancy)));
            com.Parameters.Add(new SqlParameter("@positiontype", positionType));
            com.Parameters.Add(new SqlParameter("@minsalary", GetMinSalary(salary)));
            com.Parameters.Add(new SqlParameter("@maxsalary", GetMaxSalary(salary)));
            com.Parameters.Add(new SqlParameter("@period", GetSalaryPeriod(salary)));
            com.Parameters.Add(new SqlParameter("@gender", GenderMapping(gender)));
            com.Parameters.Add(new SqlParameter("@degree", DegreeMapping(degree)));
            com.Parameters.Add(new SqlParameter("@experienced", ExperiencedMapping(experienced)));
            com.Parameters.Add(new SqlParameter("@positiondescript", positionDesctipt.Replace("<br/>", "\r\n")));
            object res = com.ExecuteScalar();
        }

        public void DoAutoRefresh()
        {
            try
            {
                string deleteitems = string.Empty;
                string refreshitems = string.Empty;
                using (System.Data.SqlClient.SqlConnection con =
                    new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectStr"].ConnectionString))
                {
                    System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(
                        "select * from RefreshRecord", con);
                    System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(com);
                    System.Data.DataSet ds = new System.Data.DataSet();
                    con.Open();
                    da.Fill(ds);
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
                        {
                            int id = Int32.Parse(dr["id"].ToString());
                            int recruitId = Int32.Parse(dr["recruitId"].ToString());
                            DateTime enddate = DateTime.Parse(dr["enddate"].ToString());
                            if (enddate <= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))
                            {
                                deleteitems += id.ToString() + ",";
                            }
                            refreshitems += recruitId.ToString() + ",";

                        }
                    }
                    if (!String.IsNullOrEmpty(refreshitems))
                    {
                        refreshitems = refreshitems.EndsWith(",") ? refreshitems.Remove(refreshitems.Length - 1) : refreshitems;
                        string sql = "update recruitsheet set refresh = '" + DateTime.Now.ToString() + "' where id in (" + refreshitems + ")";
                        com.CommandText = sql;
                        int affact = com.ExecuteNonQuery();
                        if (affact != refreshitems.Split(',').Length)
                        {
                            Console.WriteLine("执行刷新发布时间更新行数和提交行数不一致");
                        }
                    }
                    if (!String.IsNullOrEmpty(deleteitems))
                    {
                        deleteitems = deleteitems.EndsWith(",") ? deleteitems.Remove(deleteitems.Length - 1) : deleteitems;
                        string sql = "delete refreshrecord where id in (" + deleteitems + ")";
                        com.CommandText = sql;
                        int affact = com.ExecuteNonQuery();
                        if (affact != deleteitems.Split(',').Length)
                        {
                            Console.WriteLine("执行删除发布时间更新行数和提交行数不一致");
                        }
                    }

                    con.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
